package com.baomidou.pdf2swf;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * 
 * PDF 转 SWF
 * 
 * <p>
 * SwfTools 转换工具
 * 官网： http://www.swftools.org/download.html
 * </p>
 * <p>
 * Windows 下载地址： http://www.swftools.org/swftools-2013-04-09-1007.exe
 * </p>
 */
public class SwfTools {

	private static final String EXEC_COMMAND = "C:/Program Files (x86)/SWFTools/pdf2swf.exe -o %s -s flashversion=9 %s";


	public static void main( String[] args ) {
		convertAllFiles(new File("E:/pdf/"));
	}


	/**
	 * 
	 * 遍历文件夹，批量生成 SWF
	 * 
	 */
	private static void convertAllFiles( File dir ) {
		File[] fs = dir.listFiles();
		for ( int i = 0 ; i < fs.length ; i++ ) {
			if ( fs[i].isDirectory() ) {
				try {
					convertAllFiles(fs[i]);
				} catch ( Exception e ) {}
			} else {
				/**
				 * 执行生成 SWF
				 */
				String fileName = fs[i].getName();
				if(fileName.contains(".pdf")){
					try {
						String sourcePath = fs[i].getPath();
						String destFile = fs[i].getParent() + File.separator + fileName.replace(".pdf", ".swf");
						if ( !new File(destFile).exists() ) {
							/**
							 * 文件不存在执行转换
							 */
							long start = System.currentTimeMillis();
							System.err.println("------start-----");
							System.out.println("\n sourcePath = " + sourcePath);
							System.out.println("\n destFile = " + destFile);
							convertPDF2SWF(sourcePath, destFile);
							System.err.println("------------------------------------------");
							long finish = System.currentTimeMillis();
							System.out.println(" 耗时："+ (finish - start));
							System.err.println("------finish-----");
						}
						//休息 5秒
						Thread.sleep(5000);
					} catch ( Exception e ) {
						e.printStackTrace();
					}
				}
			}
		}
	}

	/**
	 * 
	 * PDF 转 SWF
	 *  
	 * @param sourcePath 
	 * 				源pdf文件
	 * @param destPath
	 * 				目标路径
	 * @param fileName
	 * 				swf文件名如：xxx.swf
	 * @return
	 * @throws IOException
	 */
	public static int convertPDF2SWF( String sourcePath, String destFile ) throws IOException {
		/**
		 * 源文件不存在则返回  
		 */
		File source = new File(sourcePath);
		if ( !source.exists() ) {
			return 0;
		}

		/**
		 * 调用pdf2swf命令进行转换  
		 */
		Process pro = Runtime.getRuntime().exec(String.format(EXEC_COMMAND, destFile, sourcePath));

		BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(pro.getInputStream()));
		while ( bufferedReader.readLine() != null )
			;

		try {
			pro.waitFor();
		} catch ( InterruptedException e ) {
			e.printStackTrace();
		}
		return pro.exitValue();
	}

}
